package com.ljw.hmall.filters;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
@Component
@Order(-1)
public class MyGlobalFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        HttpHeaders headers = exchange.getRequest().getHeaders();
        List<String> tokenList = headers.get("authorization");
        String token=null;
        if(tokenList!=null&&tokenList.size()>0){
             token = tokenList.get(0);
        }
        if (token!=null){
            if ("2".equals(token)){
                System.out.println("请求中携带了正确的token放行...");
             return chain.filter(exchange);
            }
        }
        System.out.println("请求中没有携带正确的token禁止访问服务...");
        //设置禁止访问状态码响应给客户端
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);

        //禁止路由访问微服务
        return exchange.getResponse().setComplete();
    }
}
